<?php

namespace Caifenglei\AuthRbac;

use Illuminate\Support\Facades\Gate;
use Illuminate\Support\ServiceProvider;

class AuthRbacServiceProvider extends ServiceProvider
{
    /**
     * Register services.
     */
    public function register(): void
    {
        //
    }

    /**
     * Bootstrap services.
     */
    public function boot(): void
    {
        //API Routes
        $this->loadRoutesFrom(__DIR__.'/routes/api.php');
        $this->loadRoutesFrom(__DIR__.'/routes/web.php');

        //Lang 
        $this->loadTranslationsFrom(__DIR__.'/lang', 'auth-rbac');

        //Resources publish
        $this->publishFiles();

        //超级管理员只需登录，即可访问所有权限
        Gate::before(function ($user, $ability) {
            return $user->isSuperAdmin() ? true : null;
        });
    }

    protected function publishFiles() : void
    {
        // in console only
        if (! $this->app->runningInConsole()) {
            return;
        }

        if (! function_exists('config_path')) {
            // function not available and 'publish' not relevant in Lumen
            return;
        }

        $this->publishes([
            __DIR__.'/config/permission.php' => config_path('permission.php'),
            __DIR__.'/config/auth-rbac.php' => config_path('auth-rbac.php'),
        ], 'rbac-config');

        $this->publishes([
            __DIR__.'/database/migrations/' => database_path('migrations')
        ], 'rbac-migrations');
    }
}
